'use client';

import { useState, useEffect } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { DashboardLayout } from '@/components/layout/dashboard-layout';
import { formatAddress, formatDate, formatCurrency } from '@/lib/utils';
import { multiChainApi } from '@/lib/multi-chain-api';
import { useChain } from '@/context/ChainContext';
import { 
  Clock, Users, TrendingUp, Calendar, Lock, 
  CheckCircle, XCircle, AlertCircle, Plus, 
  FileText, PieChart, ArrowRight, Download,
  User, Wallet, Timer
} from 'lucide-react';

interface VestingSchedule {
  id: string;
  beneficiary_address: string;
  beneficiary_name?: string;
  vesting_type: string;
  total_amount: number;
  released_amount: number;
  claimed_amount: number;
  vested_amount: number;
  available_to_claim: number;
  remaining_amount: number;
  start_date: string;
  end_date: string;
  cliff_date?: string;
  vesting_months: number;
  monthly_release_amount: number;
  next_release_date?: string;
  is_active: boolean;
  is_revoked: boolean;
  created_at: string;
  vesting_contract_address?: string;
  vesting_schedule_id?: string;
  creation_tx_hash?: string;
}

interface VestingStats {
  total_schedules: number;
  active_schedules: number;
  total_allocated: number;
  total_vested: number;
  total_claimed: number;
  total_remaining: number;
  by_type: Record<string, {
    count: number;
    allocated: number;
    claimed: number;
  }>;
}

interface VestingAllocation {
  allocation_type: string;
  total_allocation: number;
  allocated_amount: number;
  remaining_amount: number;
  utilization_percentage: number;
  default_vesting_months: number;
  default_cliff_months?: number;
  description?: string;
}

const vestingTypeColors: Record<string, string> = {
  founding_team: 'bg-purple-100 text-purple-800',
  technical_team: 'bg-blue-100 text-blue-800',
  operations_team: 'bg-green-100 text-green-800',
  institutional: 'bg-yellow-100 text-yellow-800',
  advisor: 'bg-pink-100 text-pink-800',
  other: 'bg-gray-100 text-gray-800'
};

const vestingTypeLabels: Record<string, string> = {
  founding_team: 'Founding Team',
  technical_team: 'Technical Team',
  operations_team: 'Operations Team',
  institutional: 'Institutional',
  advisor: 'Advisor',
  other: 'Other'
};

export default function VestingPage() {
  const queryClient = useQueryClient();
  const { currentChain } = useChain();
  const [selectedSchedule, setSelectedSchedule] = useState<VestingSchedule | null>(null);
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [showScheduleDetails, setShowScheduleDetails] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const [filterType, setFilterType] = useState<string>('all');
  const [filterStatus, setFilterStatus] = useState<string>('all');

  // Invalidate queries when chain changes
  useEffect(() => {
    queryClient.invalidateQueries();
  }, [currentChain, queryClient]);

  // Fetch vesting statistics
  const { data: stats } = useQuery<VestingStats>({
    queryKey: ['vestingStats', currentChain],
    queryFn: async () => {
      const response = await multiChainApi.getClient(currentChain).get('/api/v1/admin/vesting/stats');
      return response.data;
    },
    refetchInterval: 60000 // Refresh every minute
  });

  // Fetch vesting schedules
  const { data: schedules = [], isLoading: schedulesLoading } = useQuery<VestingSchedule[]>({
    queryKey: ['vestingSchedules', currentChain, filterType, filterStatus, searchTerm],
    queryFn: async () => {
      const params = new URLSearchParams();
      if (filterType !== 'all') params.append('vesting_type', filterType);
      if (filterStatus === 'active') params.append('is_active', 'true');
      if (filterStatus === 'revoked') params.append('is_active', 'false');
      if (searchTerm) params.append('beneficiary', searchTerm);
      
      const response = await multiChainApi.getClient(currentChain).get(`/api/v1/admin/vesting/schedules?${params}`);
      return response.data;
    }
  });

  // Fetch vesting allocations
  const { data: allocations = [] } = useQuery<VestingAllocation[]>({
    queryKey: ['vestingAllocations', currentChain],
    queryFn: async () => {
      const response = await multiChainApi.getClient(currentChain).get('/api/v1/admin/vesting/allocations');
      return response.data;
    }
  });

  // Initialize allocations mutation
  const initializeAllocationsMutation = useMutation({
    mutationFn: async () => {
      return multiChainApi.getClient(currentChain).post('/api/v1/admin/vesting/allocations/initialize');
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['vestingAllocations', currentChain] });
    }
  });

  // Revoke schedule mutation
  const revokeScheduleMutation = useMutation({
    mutationFn: async (scheduleId: string) => {
      return multiChainApi.getClient(currentChain).post(`/api/v1/admin/vesting/schedules/${scheduleId}/revoke`);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['vestingSchedules', currentChain] });
      queryClient.invalidateQueries({ queryKey: ['vestingStats', currentChain] });
      setShowScheduleDetails(false);
    }
  });

  const getProgressPercentage = (schedule: VestingSchedule) => {
    return (schedule.vested_amount / schedule.total_amount) * 100;
  };

  const getClaimedPercentage = (schedule: VestingSchedule) => {
    return (schedule.claimed_amount / schedule.total_amount) * 100;
  };

  return (
    <DashboardLayout>
      <div className="space-y-6">
        {/* Header */}
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-3xl font-bold">Token Vesting</h1>
            <p className="text-muted-foreground">
              Manage team and institutional vesting schedules
            </p>
          </div>
          <div className="flex gap-2">
            {allocations.length === 0 && (
              <Button
                variant="outline"
                onClick={() => initializeAllocationsMutation.mutate()}
                disabled={initializeAllocationsMutation.isPending}
              >
                Initialize Allocations
              </Button>
            )}
            <Button onClick={() => setShowCreateModal(true)}>
              <Plus className="h-4 w-4 mr-2" />
              Create Schedule
            </Button>
          </div>
        </div>

        {/* Statistics Cards */}
        <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Total Schedules</CardTitle>
              <Users className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{stats?.total_schedules || 0}</div>
              <p className="text-xs text-muted-foreground">
                {stats?.active_schedules || 0} active
              </p>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Total Allocated</CardTitle>
              <Lock className="h-4 w-4 text-blue-600" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">
                {formatCurrency(stats?.total_allocated || 0, 'DTV')}
              </div>
              <p className="text-xs text-muted-foreground">
                Across all schedules
              </p>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Total Vested</CardTitle>
              <TrendingUp className="h-4 w-4 text-green-600" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">
                {formatCurrency(stats?.total_vested || 0, 'DTV')}
              </div>
              <p className="text-xs text-muted-foreground">
                {stats?.total_claimed || 0} claimed
              </p>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Remaining</CardTitle>
              <Clock className="h-4 w-4 text-yellow-600" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">
                {formatCurrency(stats?.total_remaining || 0, 'DTV')}
              </div>
              <p className="text-xs text-muted-foreground">
                To be vested
              </p>
            </CardContent>
          </Card>
        </div>

        {/* Allocation Overview */}
        {allocations.length > 0 && (
          <Card>
            <CardHeader>
              <CardTitle>Allocation Overview</CardTitle>
              <CardDescription>Token allocation limits by category</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                {allocations.map((allocation) => (
                  <div key={allocation.allocation_type} className="space-y-2">
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-2">
                        <span className={`px-2 py-1 rounded-full text-xs ${vestingTypeColors[allocation.allocation_type]}`}>
                          {vestingTypeLabels[allocation.allocation_type]}
                        </span>
                        <span className="text-sm text-muted-foreground">
                          {allocation.description}
                        </span>
                      </div>
                      <div className="text-right">
                        <p className="text-sm font-medium">
                          {formatCurrency(allocation.allocated_amount, 'DTV')} / {formatCurrency(allocation.total_allocation, 'DTV')}
                        </p>
                        <p className="text-xs text-muted-foreground">
                          {allocation.utilization_percentage.toFixed(1)}% utilized
                        </p>
                      </div>
                    </div>
                    <div className="w-full bg-gray-200 rounded-full h-2">
                      <div
                        className="bg-blue-600 h-2 rounded-full"
                        style={{ width: `${allocation.utilization_percentage}%` }}
                      />
                    </div>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        )}

        {/* Vesting Schedules */}
        <Card>
          <CardHeader>
            <CardTitle>Vesting Schedules</CardTitle>
            <CardDescription>All beneficiary vesting schedules</CardDescription>
          </CardHeader>
          <CardContent>
            {/* Filters */}
            <div className="flex gap-4 mb-6">
              <input
                type="text"
                placeholder="Search by address or name..."
                className="flex-1 px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
              />
              <select
                className="px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                value={filterType}
                onChange={(e) => setFilterType(e.target.value)}
              >
                <option value="all">All Types</option>
                {Object.entries(vestingTypeLabels).map(([value, label]) => (
                  <option key={value} value={value}>{label}</option>
                ))}
              </select>
              <select
                className="px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                value={filterStatus}
                onChange={(e) => setFilterStatus(e.target.value)}
              >
                <option value="all">All Status</option>
                <option value="active">Active</option>
                <option value="revoked">Revoked</option>
              </select>
            </div>

            {/* Schedules List */}
            <div className="space-y-4">
              {schedulesLoading ? (
                <div className="text-center p-8 text-muted-foreground">
                  Loading schedules...
                </div>
              ) : schedules.length > 0 ? (
                schedules.map((schedule) => (
                  <div
                    key={schedule.id}
                    className="border rounded-lg p-4 hover:bg-muted/50 cursor-pointer"
                    onClick={() => {
                      setSelectedSchedule(schedule);
                      setShowScheduleDetails(true);
                    }}
                  >
                    <div className="flex items-center justify-between">
                      <div className="space-y-2">
                        <div className="flex items-center gap-2">
                          <User className="h-4 w-4 text-muted-foreground" />
                          <span className="font-medium">
                            {schedule.beneficiary_name || formatAddress(schedule.beneficiary_address)}
                          </span>
                          <span className={`px-2 py-1 rounded-full text-xs ${vestingTypeColors[schedule.vesting_type]}`}>
                            {vestingTypeLabels[schedule.vesting_type]}
                          </span>
                          {schedule.is_revoked && (
                            <span className="px-2 py-1 rounded-full text-xs bg-red-100 text-red-800">
                              Revoked
                            </span>
                          )}
                        </div>
                        <div className="flex items-center gap-4 text-sm text-muted-foreground">
                          <span>Total: {formatCurrency(schedule.total_amount, 'DTV')}</span>
                          <span>Vested: {formatCurrency(schedule.vested_amount, 'DTV')}</span>
                          <span>Claimed: {formatCurrency(schedule.claimed_amount, 'DTV')}</span>
                          <span>Available: {formatCurrency(schedule.available_to_claim, 'DTV')}</span>
                        </div>
                        <div className="flex items-center gap-4 text-xs text-muted-foreground">
                          <span className="flex items-center gap-1">
                            <Calendar className="h-3 w-3" />
                            {formatDate(schedule.start_date)} - {formatDate(schedule.end_date)}
                          </span>
                          <span className="flex items-center gap-1">
                            <Timer className="h-3 w-3" />
                            {schedule.vesting_months} months
                          </span>
                          {schedule.next_release_date && (
                            <span className="flex items-center gap-1">
                              <ArrowRight className="h-3 w-3" />
                              Next: {formatDate(schedule.next_release_date)}
                            </span>
                          )}
                        </div>
                      </div>
                      <div className="text-right space-y-2">
                        <div className="text-sm font-medium">
                          {getProgressPercentage(schedule).toFixed(1)}% vested
                        </div>
                        <div className="w-32 bg-gray-200 rounded-full h-2">
                          <div className="relative h-2">
                            <div
                              className="absolute bg-blue-400 h-2 rounded-full"
                              style={{ width: `${getProgressPercentage(schedule)}%` }}
                            />
                            <div
                              className="absolute bg-blue-600 h-2 rounded-full"
                              style={{ width: `${getClaimedPercentage(schedule)}%` }}
                            />
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                ))
              ) : (
                <div className="text-center p-8 text-muted-foreground">
                  No vesting schedules found
                </div>
              )}
            </div>
          </CardContent>
        </Card>

        {/* Schedule Details Modal */}
        {showScheduleDetails && selectedSchedule && (
          <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
            <Card className="w-full max-w-2xl max-h-[90vh] overflow-y-auto">
              <CardHeader>
                <div className="flex items-center justify-between">
                  <div>
                    <CardTitle>Vesting Schedule Details</CardTitle>
                    <CardDescription>
                      {selectedSchedule.beneficiary_name || formatAddress(selectedSchedule.beneficiary_address)}
                    </CardDescription>
                  </div>
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => setShowScheduleDetails(false)}
                  >
                    ✕
                  </Button>
                </div>
              </CardHeader>
              <CardContent className="space-y-6">
                {/* Schedule Info */}
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="text-sm font-medium">Type</label>
                    <p className="mt-1">
                      <span className={`px-2 py-1 rounded-full text-xs ${vestingTypeColors[selectedSchedule.vesting_type]}`}>
                        {vestingTypeLabels[selectedSchedule.vesting_type]}
                      </span>
                    </p>
                  </div>
                  <div>
                    <label className="text-sm font-medium">Status</label>
                    <p className="mt-1">
                      {selectedSchedule.is_revoked ? (
                        <span className="flex items-center gap-1 text-red-600">
                          <XCircle className="h-4 w-4" />
                          Revoked
                        </span>
                      ) : selectedSchedule.is_active ? (
                        <span className="flex items-center gap-1 text-green-600">
                          <CheckCircle className="h-4 w-4" />
                          Active
                        </span>
                      ) : (
                        <span className="flex items-center gap-1 text-gray-600">
                          <AlertCircle className="h-4 w-4" />
                          Inactive
                        </span>
                      )}
                    </p>
                  </div>
                </div>

                {/* Amount Details */}
                <div className="space-y-4">
                  <h4 className="font-medium">Amount Details</h4>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="text-sm text-muted-foreground">Total Amount</label>
                      <p className="text-lg font-medium">{formatCurrency(selectedSchedule.total_amount, 'DTV')}</p>
                    </div>
                    <div>
                      <label className="text-sm text-muted-foreground">Monthly Release</label>
                      <p className="text-lg font-medium">{formatCurrency(selectedSchedule.monthly_release_amount, 'DTV')}</p>
                    </div>
                    <div>
                      <label className="text-sm text-muted-foreground">Vested Amount</label>
                      <p className="text-lg font-medium text-blue-600">{formatCurrency(selectedSchedule.vested_amount, 'DTV')}</p>
                    </div>
                    <div>
                      <label className="text-sm text-muted-foreground">Claimed Amount</label>
                      <p className="text-lg font-medium text-green-600">{formatCurrency(selectedSchedule.claimed_amount, 'DTV')}</p>
                    </div>
                    <div>
                      <label className="text-sm text-muted-foreground">Available to Claim</label>
                      <p className="text-lg font-medium text-yellow-600">{formatCurrency(selectedSchedule.available_to_claim, 'DTV')}</p>
                    </div>
                    <div>
                      <label className="text-sm text-muted-foreground">Remaining to Vest</label>
                      <p className="text-lg font-medium text-gray-600">{formatCurrency(selectedSchedule.remaining_amount, 'DTV')}</p>
                    </div>
                  </div>
                </div>

                {/* Vesting Progress */}
                <div className="space-y-2">
                  <h4 className="font-medium">Vesting Progress</h4>
                  <div className="space-y-4">
                    <div>
                      <div className="flex justify-between text-sm mb-1">
                        <span>Overall Progress</span>
                        <span>{getProgressPercentage(selectedSchedule).toFixed(1)}%</span>
                      </div>
                      <div className="w-full bg-gray-200 rounded-full h-3">
                        <div
                          className="bg-blue-600 h-3 rounded-full"
                          style={{ width: `${getProgressPercentage(selectedSchedule)}%` }}
                        />
                      </div>
                    </div>
                    <div>
                      <div className="flex justify-between text-sm mb-1">
                        <span>Claimed</span>
                        <span>{getClaimedPercentage(selectedSchedule).toFixed(1)}%</span>
                      </div>
                      <div className="w-full bg-gray-200 rounded-full h-3">
                        <div
                          className="bg-green-600 h-3 rounded-full"
                          style={{ width: `${getClaimedPercentage(selectedSchedule)}%` }}
                        />
                      </div>
                    </div>
                  </div>
                </div>

                {/* Schedule Dates */}
                <div className="space-y-4">
                  <h4 className="font-medium">Schedule Timeline</h4>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="text-sm text-muted-foreground">Start Date</label>
                      <p className="font-medium">{formatDate(selectedSchedule.start_date)}</p>
                    </div>
                    <div>
                      <label className="text-sm text-muted-foreground">End Date</label>
                      <p className="font-medium">{formatDate(selectedSchedule.end_date)}</p>
                    </div>
                    {selectedSchedule.cliff_date && (
                      <div>
                        <label className="text-sm text-muted-foreground">Cliff Date</label>
                        <p className="font-medium">{formatDate(selectedSchedule.cliff_date)}</p>
                      </div>
                    )}
                    {selectedSchedule.next_release_date && (
                      <div>
                        <label className="text-sm text-muted-foreground">Next Release</label>
                        <p className="font-medium">{formatDate(selectedSchedule.next_release_date)}</p>
                      </div>
                    )}
                  </div>
                </div>

                {/* Contract Info */}
                {selectedSchedule.vesting_contract_address && (
                  <div className="space-y-2">
                    <h4 className="font-medium">Contract Information</h4>
                    <div className="space-y-2 text-sm">
                      <div>
                        <label className="text-muted-foreground">Contract Address</label>
                        <p className="font-mono">{selectedSchedule.vesting_contract_address}</p>
                      </div>
                      {selectedSchedule.vesting_schedule_id && (
                        <div>
                          <label className="text-muted-foreground">Schedule ID</label>
                          <p className="font-mono">{selectedSchedule.vesting_schedule_id}</p>
                        </div>
                      )}
                      {selectedSchedule.creation_tx_hash && (
                        <div>
                          <label className="text-muted-foreground">Creation TX</label>
                          <p className="font-mono">{selectedSchedule.creation_tx_hash}</p>
                        </div>
                      )}
                    </div>
                  </div>
                )}

                {/* Actions */}
                {selectedSchedule.is_active && !selectedSchedule.is_revoked && (
                  <div className="flex justify-end gap-2 pt-4 border-t">
                    <Button
                      variant="danger"
                      onClick={() => {
                        if (confirm('Are you sure you want to revoke this vesting schedule? This action cannot be undone.')) {
                          revokeScheduleMutation.mutate(selectedSchedule.id);
                        }
                      }}
                      disabled={revokeScheduleMutation.isPending}
                    >
                      Revoke Schedule
                    </Button>
                  </div>
                )}
              </CardContent>
            </Card>
          </div>
        )}

        {/* Create Schedule Modal */}
        {showCreateModal && (
          <CreateVestingScheduleModal
            onClose={() => setShowCreateModal(false)}
            allocations={allocations}
          />
        )}
      </div>
    </DashboardLayout>
  );
}

// Create Schedule Modal Component
function CreateVestingScheduleModal({
  onClose,
  allocations
}: {
  onClose: () => void;
  allocations: VestingAllocation[];
}) {
  const queryClient = useQueryClient();
  const { currentChain } = useChain();
  const [formData, setFormData] = useState({
    beneficiary_address: '',
    beneficiary_name: '',
    vesting_type: 'founding_team',
    total_amount: '',
    vesting_months: 84,
    cliff_months: 12,
    notes: ''
  });

  const createScheduleMutation = useMutation({
    mutationFn: async (data: any) => {
      return multiChainApi.getClient(currentChain).post('/api/v1/admin/vesting/schedules', data);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['vestingSchedules', currentChain] });
      queryClient.invalidateQueries({ queryKey: ['vestingStats', currentChain] });
      queryClient.invalidateQueries({ queryKey: ['vestingAllocations', currentChain] });
      onClose();
    }
  });

  const selectedAllocation = allocations.find(a => a.allocation_type === formData.vesting_type);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    createScheduleMutation.mutate({
      ...formData,
      total_amount: parseFloat(formData.total_amount),
      cliff_months: formData.cliff_months || null
    });
  };

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
      <Card className="w-full max-w-lg">
        <CardHeader>
          <div className="flex items-center justify-between">
            <CardTitle>Create Vesting Schedule</CardTitle>
            <Button
              variant="ghost"
              size="sm"
              onClick={onClose}
            >
              ✕
            </Button>
          </div>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSubmit} className="space-y-4">
            <div>
              <label className="block text-sm font-medium mb-1">Beneficiary Address</label>
              <input
                type="text"
                className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                value={formData.beneficiary_address}
                onChange={(e) => setFormData({...formData, beneficiary_address: e.target.value})}
                placeholder="0x..."
                required
              />
            </div>

            <div>
              <label className="block text-sm font-medium mb-1">Beneficiary Name (Optional)</label>
              <input
                type="text"
                className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                value={formData.beneficiary_name}
                onChange={(e) => setFormData({...formData, beneficiary_name: e.target.value})}
                placeholder="John Doe"
              />
            </div>

            <div>
              <label className="block text-sm font-medium mb-1">Vesting Type</label>
              <select
                className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                value={formData.vesting_type}
                onChange={(e) => {
                  const allocation = allocations.find(a => a.allocation_type === e.target.value);
                  setFormData({
                    ...formData,
                    vesting_type: e.target.value,
                    vesting_months: allocation?.default_vesting_months || 84,
                    cliff_months: allocation?.default_cliff_months || 0
                  });
                }}
              >
                {allocations.map((allocation) => (
                  <option key={allocation.allocation_type} value={allocation.allocation_type}>
                    {vestingTypeLabels[allocation.allocation_type]} 
                    ({formatCurrency(allocation.remaining_amount, 'DTV')} available)
                  </option>
                ))}
              </select>
              {selectedAllocation && (
                <p className="text-xs text-muted-foreground mt-1">
                  {selectedAllocation.description}
                </p>
              )}
            </div>

            <div>
              <label className="block text-sm font-medium mb-1">Total Amount (DTV)</label>
              <input
                type="number"
                className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                value={formData.total_amount}
                onChange={(e) => setFormData({...formData, total_amount: e.target.value})}
                placeholder="100000"
                min="1"
                max={selectedAllocation?.remaining_amount.toString()}
                step="0.01"
                required
              />
              {selectedAllocation && (
                <p className="text-xs text-muted-foreground mt-1">
                  Maximum: {formatCurrency(selectedAllocation.remaining_amount, 'DTV')}
                </p>
              )}
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium mb-1">Vesting Period (Months)</label>
                <input
                  type="number"
                  className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  value={formData.vesting_months}
                  onChange={(e) => setFormData({...formData, vesting_months: parseInt(e.target.value)})}
                  min="1"
                  max="120"
                  required
                />
              </div>
              <div>
                <label className="block text-sm font-medium mb-1">Cliff Period (Months)</label>
                <input
                  type="number"
                  className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  value={formData.cliff_months}
                  onChange={(e) => setFormData({...formData, cliff_months: parseInt(e.target.value)})}
                  min="0"
                  max="24"
                />
              </div>
            </div>

            <div>
              <label className="block text-sm font-medium mb-1">Notes (Optional)</label>
              <textarea
                className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                value={formData.notes}
                onChange={(e) => setFormData({...formData, notes: e.target.value})}
                rows={3}
                placeholder="Additional notes..."
              />
            </div>

            <div className="flex justify-end gap-2 pt-4">
              <Button
                type="button"
                variant="outline"
                onClick={onClose}
              >
                Cancel
              </Button>
              <Button
                type="submit"
                disabled={createScheduleMutation.isPending}
              >
                {createScheduleMutation.isPending ? 'Creating...' : 'Create Schedule'}
              </Button>
            </div>
          </form>
        </CardContent>
      </Card>
    </div>
  );
}